<?php
namespace App\Api\Fcjd;

use PhalApi\Api;
use App\Domain\Fcjd\Tags as TagsDomain;
use PhalApi\Exception\BadRequestException;

/**
 * 任务获取接口
 * @author wenfree 20240118
 */
class Task extends Api {
    public function getRules() {
        return array(
            'getAll' => array(
                'oaid' => array('name' => 'oaid', 'require' => true, 'min' => 1, 'desc' => '设备唯一标识'),
            ),
            'getAllpay' => array(
                'oaid' => array('name' => 'oaid', 'require' => true, 'min' => 1, 'desc' => '设备唯一标识'),
            ),
        );
    }

    /**
     * 获取带提现设置的任务
     * @desc 一次性获取所有可执行任务
     * @return array tasks 任务列表
     * @return array app_info 应用信息
     * @return array tags 任务标签
     * @return array banners 广告图
     * @return array auto_files 动态文件
     */
    public function getAllpay() {
        // 处理跨域
        // 处理跨域
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *,x-token,X-token');

        // 获取设备信息
        $device = \PhalApi\DI()->notorm->phone_list
            ->where('oaid', $this->oaid)
            ->order('time_line desc')
            ->fetchOne();

        if (!$device) {
            throw new BadRequestException('设备未注册');
        }

        if ($device['time_line'] < date('Y-m-d H:i:s', time())) {
            $tasks = \PhalApi\DI()->notorm->phone_app
                ->select('*')
                ->where(array('id' => '47'))
                ->fetchAll();
            \PhalApi\DI()->response->setMsg('success');
            return $tasks;
        }

        // 更新设备信息
        $update_data = array(
            'update_time' => date('Y-m-d H:i:s', time())
        );

        \PhalApi\DI()->notorm
            ->phone_list
            ->where('oaid', $this->oaid)
            ->update($update_data);

        $task_date = $device['task_date'];
        $task_day = $device['task_day'];

        // 获取当前日期和任务日期
		$currentDate = date_create(); // 当前日期
		$selectedDate = date_create($device['task_date']); // 任务日期
		// 计算时间差（自动处理绝对值）
		$diff = date_diff($currentDate, $selectedDate);
		$diffDays = $diff->days; // 总天数差（如2天则返回2）
		// 计算商（向下取整）
		$quotient = (int)floor($diffDays / $device['task_day']);
        $task_key = $quotient%2 == 0 ? 'task' : 'task2';

        // return [$task_date, $task_day, $quotient];
        // 获取所有可执行任务
        $applist = $device[$task_key];
        if ($applist) {
            $applist = explode(',', $applist);
        }

        $tasks = \PhalApi\DI()->notorm
            ->phone_app
            ->select('*')
            ->where(array('id' => $applist, 'state' => 1))
            ->fetchAll();

        $taskPay = \PhalApi\DI()->notorm
            ->phone_app_info
            ->select('app_name,config')
            ->where(array('mobile' => $device['mobile']))
            ->fetchAll();

        // 创建一个关联数组，以 app_name 为键，config 为值
        $configMap = [];
        foreach ($taskPay as $item) {
            $configMap[$item['app_name']] = $item['config'] ? $item['config'] : '{"withdrawType":"小额支付宝自动提现"}';
        }
        // return [$configMap];
        // 遍历第一个数组，更新 config 字段
        foreach ($tasks as &$item) {
            if (isset($configMap[$item['name']])) {
                $item['config'] = $configMap[$item['name']];
            }
        }

        // 获取游戏标签
        $tagsDomain = new TagsDomain();
        foreach ($tasks as $key => $task) {
            if( $task['script_name'] === '百度-推荐官' ){
                $tasks[$key]['tags'] = $tagsDomain->getAllTagsByTypeForBD($task['tag_name']);
            }else{
                $tasks[$key]['tags'] = $tagsDomain->getTagsByType($task['tag_name']);
            }
        }
        \PhalApi\DI()->response->setMsg('success');
        return $tasks;
    }


    /**
     * 获取所有任务
     * @desc 一次性获取所有可执行任务
     * @return array tasks 任务列表
     * @return array app_info 应用信息
     * @return array tags 任务标签
     * @return array banners 广告图
     * @return array auto_files 动态文件
     */
    public function getAll() {
        // 处理跨域
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *,x-token,X-token');

        // 获取设备信息
        $device = \PhalApi\DI()->notorm->phone_list
            ->where('oaid', $this->oaid)
            ->order('time_line desc')
            ->fetchOne();

        if (!$device) {
            throw new BadRequestException('设备未注册');
        }

        if ($device['time_line'] < date('Y-m-d H:i:s', time())) {
            $tasks = \PhalApi\DI()->notorm->phone_app
                ->select('*')
                ->where(array('id' => '47'))
                ->fetchAll();
            \PhalApi\DI()->response->setMsg('success');
            return $tasks;
        }

        // 更新设备信息
        $update_data = array(
            'update_time' => date('Y-m-d H:i:s', time())
        );

        \PhalApi\DI()->notorm->phone_list
            ->where('oaid', $this->oaid)
            ->update($update_data);

        // 获取当前日期和任务日期
        $currentDate = date_create(); // 当前日期
        $selectedDate = date_create($device['task_date']); // 任务日期
        // 计算时间差（自动处理绝对值）
        $diff = date_diff($currentDate, $selectedDate);
        $diffDays = $diff->days; // 总天数差（如2天则返回2）
        // 计算商（向下取整）
        $quotient = (int)floor($diffDays / $device['task_day']);
        $task_key = $quotient % 2 == 0 ? 'task' : 'task2';

        // return [$task_date, $task_day, $quotient];
        // 获取所有可执行任务
        $applist = $device[$task_key];
        if ($applist) {
            $applist = explode(',', $applist);
        }

        $tasks = \PhalApi\DI()->notorm->phone_app
            ->select('*')
            ->where(array('id' => $applist, 'state' => 1))
            ->fetchAll();

        $taskPay = \PhalApi\DI()->notorm
                    ->phone_app_info
                    ->select('app_name,config')
                    ->where(array('mobile' => $device['mobile']))
                    ->fetchAll();

        // 创建一个关联数组，以 app_name 为键，config 为值
        $configMap = [];
        foreach ($taskPay as $item) {
            $configMap[$item['app_name']] = $item['config'] ? $item['config']: '{"withdrawType":"小额支付宝自动提现"}';
        }
        // return [$configMap];
        // 遍历第一个数组，更新 config 字段
        foreach ($tasks as &$item) {
            if (isset($configMap[$item['name']])) {
                $item['config'] = $configMap[$item['name']];
            }
        }
        
        // 获取游戏标签
        $tagsDomain = new TagsDomain();
        foreach ($tasks as $key => $task) {
            if( $task['script_name'] === '百度-推荐官' ){
                $tasks[$key]['tags'] = $tagsDomain->getAllTagsByTypeForBD($task['tag_name']);
            }else{
                $tasks[$key]['tags'] = $tagsDomain->getTagsByType($task['tag_name']);
            }
        }
        \PhalApi\DI()->response->setMsg('success');
        return $tasks;
    }
}